package com.ctsi.organise.app.rest;

import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.common.response.UnifiedResponse;
import com.ctsi.framework.mybatis.support.VoTemplate;
import com.ctsi.framework.organise.security.UserInfo;
import com.ctsi.framework.security.util.SecurityUtil;
import com.ctsi.organise.dto.PersonTreeNodeDTO;
import com.ctsi.organise.dto.UserLoginTreeNodeDTO;
import com.ctsi.organise.entity.PersonEntity;
import com.ctsi.organise.entity.UserLoginEntity;
import com.ctsi.organise.query.PersonQuery;
import com.ctsi.organise.service.IOrganiseService;
import com.ctsi.organise.service.PersonEntityManager;
import com.ctsi.organise.service.UserLoginEntityManager;
import com.ctsi.organise.vo.AddPersonVO;
import com.ctsi.organise.vo.EditPersonVO;
import com.ctsi.organise.vo.PersonVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * @author: zhangjw
 * @Date: 2018/11/16 05:41
 * @Description:
 */
@RestController
public class PersonController {

    @Autowired
    private IOrganiseService organiseService;
    @Autowired
    private PersonEntityManager personEntityManager;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private VoTemplate voTemplate;
    @Autowired
    private UserLoginEntityManager userLoginEntityManager;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @PostMapping(value = "/person/query",consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public UnifiedResponse<Page<PersonVO>> query(@RequestBody PersonQuery query){
        Page<PersonVO> page = organiseService.personPageQueryPrivileged(query, SecurityUtil.getUser().getLoginId(), query.getStart(), query.getPageSize());
        return UnifiedResponse.ok(page);
    }

    /**
     * 逻辑删除
     * @param partyIds
     * @return
     */
    @DeleteMapping(value = "/person/logic/{partyIds}")
    public UnifiedResponse<Void> delete(@PathVariable("partyIds") String partyIds){
        if (UtilValidate.isNotEmpty(partyIds)) {
            String[] ids = partyIds.split(",");
            organiseService.logicallyDeletePerson(SecurityUtil.getUser().getLoginId(), Arrays.asList(ids));
        }
        return UnifiedResponse.ok();
    }
    /*
     * 修改密码
     * */
    @PostMapping(value = "/person/editPassword",consumes = "application/json",produces = "application/json;charset=UTF-8")
    public UnifiedResponse<Void> updateLoginPsw(@RequestBody UserLoginEntity userLoginEntity){
//        java正则表达式校验密码必须是包含大小写字母、数字、特殊符号的8位以上组合
        String PW_PATTERN = "^(?![A-Za-z0-9]+$)(?![a-z0-9\\W]+$)(?![A-Za-z\\W]+$)(?![A-Z0-9\\W]+$)[a-zA-Z0-9\\W]{8,}$";
        String partyId =  userLoginEntity.getPartyId();
        if (UtilValidate.isEmpty(partyId)) {
            userLoginEntity.setPartyId(SecurityUtil.getUser().getUserId());
        }
        if (userLoginEntity.getPassword().matches(PW_PATTERN)==true){
            String encode = passwordEncoder.encode(userLoginEntity.getPassword());
            userLoginEntity.setPassword(encode);
            userLoginEntity.setModifyPwdDate(System.currentTimeMillis());
            int i = userLoginEntityManager.updateLoginPsw(userLoginEntity);
            return UnifiedResponse.ok();
        }else {
            return UnifiedResponse.error("1003","必须包含大小写字母、数字、特殊符号的8位以上组合!");
        }
    }
    /**
     * 物理删除
     * @param partyIds
     * @return
     */
    @DeleteMapping(value = "/person/physic/{partyIds}")
    public UnifiedResponse<Void> physicsDel(@PathVariable("partyIds") String partyIds){
        if(UtilValidate.isNotEmpty(partyIds)){
            String[] ids = partyIds.split(",");
        }
        return UnifiedResponse.ok();
    }
    /**
     * 编解人员信息
     * @param partyId
     * @return
     */
    @GetMapping(value="/person/{partyId}")
    public UnifiedResponse<PersonEntity> edit(@PathVariable("partyId") String partyId){
        PersonEntity personEntity = personEntityManager.findPersonEntityById(partyId);
        return UnifiedResponse.ok(personEntity);
    }

    /**
     * 根据人员手机号查询userId
     */
    @GetMapping(value="/person/{phone}")
    public UnifiedResponse<PersonEntity> selectIdByPhone(@PathVariable("phone") String phone){
        PersonEntity personEntity = personEntityManager.findPersonEntityById(phone);
        return UnifiedResponse.ok(personEntity);
    }
    /**
     * 更新人员信息
     * @param
     * @return
     */
    @PutMapping(value = "/person/update",consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public UnifiedResponse<Void> update(@RequestBody EditPersonVO editPersonVO){
        PersonEntity personEntity = voTemplate.defaultExcute(new PersonEntity(), editPersonVO);
        personEntity.setFullName(editPersonVO.getFirstName()+editPersonVO.getLastName());
        personEntityManager.updatePersonEntityByPKSelective(personEntity);
        return UnifiedResponse.ok();
    }


    @PostMapping(value = "/person/add",consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public UnifiedResponse<String> add(@RequestBody AddPersonVO personVO){
        // 检测手机
        String mobilePhone = personVO.getMobilePhone();
        Long o = (Long) personEntityManager.selectPersonByPhone(mobilePhone);
        Long o1 = (Long) personEntityManager.selectUserLoginByPhone(mobilePhone);
        if(o==0&&o1==0){
            String s = organiseService.addPersonWithAcc(personVO, SecurityUtil.getUser().getLoginId(), true);
            return UnifiedResponse.ok(s);
        }else {
            return UnifiedResponse.error("1002",mobilePhone+"手机号已存在！","");
        }
    }


    /**
     * 用户树数据，懒加载
     * @param organId
     * @return
     */
    @PostMapping(value = "/person/usertree/{organId}")
    public UnifiedResponse<List<PersonTreeNodeDTO>> userTree(@PathVariable("organId") String organId){
        UserInfo info = SecurityUtil.getUser();
        String userId = info.getLoginId();
        List<PersonTreeNodeDTO> result = this.personEntityManager.findChildNodeByParentId(info.getLoginId(),organId,"");
        return UnifiedResponse.ok(result);
    }

    /**
     * 登陆用户树，懒加载
     * @param organId
     * @return
     */
    @GetMapping(value = "/person/user-login-tree/{organId}")
    public UnifiedResponse<List<UserLoginTreeNodeDTO>> userLoginTree(@PathVariable("organId") String organId){
        UserInfo info = SecurityUtil.getUser();
        List<UserLoginTreeNodeDTO> result = personEntityManager.findChildUserLoginNodeByParentId(info.getLoginId(), organId);
        return UnifiedResponse.ok(result);
    }

    /**
     * 人员移动 1
     * @param personId
     * @param srcOrganId
     * @param destOrganId
     * @return
     */
    @PostMapping(value="/person/move")
    public UnifiedResponse<Void> movePerson(@RequestParam(value = "personId") String personId,
                                            @RequestParam(value = "srcOrganId") String srcOrganId,
                                            @RequestParam(value = "destOrganId") String destOrganId){

        personEntityManager.personMove(personId,srcOrganId,destOrganId);
        return UnifiedResponse.ok();
    }

}
